﻿using System.Collections.Generic;
using Common.Utils;
using Common.Utils.Helper;
using USClientKernel.Template;
using UnityEngine;

namespace Game.Logic.Manager
{
    public class GameConfigManager : Singleton<GameConfigManager>
    {
        private Dictionary<string, CSharpLuaTable> m_dictConfigs;
        public Dictionary<string, CSharpLuaTable> Configs { get => m_dictConfigs; set => m_dictConfigs = value; }

        protected override void Init()
        {
            Configs = new Dictionary<string, CSharpLuaTable>();
        }

        public CSharpLuaTable GetConfig(string _name)
        {
            Configs.TryGetValue(FormatConfigName(_name), out CSharpLuaTable rt);
            return rt;
        }

        public CSharpLuaTable LoadConfig(string _name)
        {
            CSharpLuaTable rt = GetConfig(_name);
            if (null != rt)
                return rt;

            string path = FormatConfigPath(_name);
            Debug.LogFormat("load config {0}", path);
            TextAsset textAsset = (TextAsset)ResManager.Instance.Load(path);
            rt = CSharpLuaTable.ParseFromStringEx(textAsset.text);

            Configs.Add(FormatConfigName(_name), rt);
            return rt;
        }

        public CSharpLuaTable LoadOrCreateConfig(string _name)
        {
            CSharpLuaTable rt = LoadConfig(_name);
            if (null != rt)
                return rt;

            rt = new CSharpLuaTable();
            Configs.Add(FormatConfigName(_name), rt);
            return rt;
        }

        private string FormatConfigPath(string _name)
        {
            _name = FormatConfigName(_name);
            return string.Concat(GameDefine.GAME_PATH_CONFIG, "/", _name, ".txt"); ;
        }

        private string FormatConfigName(string _name)
        {
            int check = _name.LastIndexOf("/", System.StringComparison.Ordinal);
            if (check > 0)
                _name = _name.Substring(check + 1, _name.Length - check - 1);
            if (_name.EndsWith(".lua", System.StringComparison.Ordinal))
                _name = _name.Substring(0, _name.Length - 4);
            return _name;
        }
    }
}
